package com.hangzhou.xyj.engine;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.hangzhou.xyj.event.TimeOutEvent;
import com.hangzhou.xyj.event.base.EventCode;
import com.hangzhou.xyj.utils.EventBusUtil;

/**
 * Created by dfb on 2015/8/26.
 * 超时处理器
 */
public class TimeOutHandler extends Handler {

    private static final String TAG = TimeOutHandler.class.getSimpleName();

    private static final int MSG_TIME_OUT = 1;

    private boolean isTimeOut = false;  //是否超时

    private long timeOut = 5000;   //超时时间，默认5s

    private TimeOutEvent event;

    private Object eventTag;

    /**
     * 一定要标识管理哪个超时事件
     */
    public TimeOutHandler(Object eventTag) {
        event = new TimeOutEvent();
        if (eventTag != null) {
            this.eventTag = eventTag;
            event.setTag(eventTag);
        }
    }

    public TimeOutHandler() {
        this(null);
    }

    public Object getEventTag() {
        return eventTag;
    }

    public void setEventTag(Object eventTag) {
        event.setTag(eventTag);
        this.eventTag = eventTag;
    }

    /**
     * 是否已超时
     */
    public boolean isTimeOut() {
        return isTimeOut;
    }

    public long getTimeOut() {
        return timeOut;
    }

    /**
     * 设置超时时间
     */
    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public void start() {
        Log.d(TAG, "TimeOutHandler ===" + event.getTag() + " ===start");
        isTimeOut = false;
        cancel();
        sendEmptyMessageDelayed(MSG_TIME_OUT, timeOut);

        //发送超时机制开始事件
        event.setCode(EventCode.START);
        EventBusUtil.postEvent(event);
    }

    public void cancel() {
        if (hasMessages(MSG_TIME_OUT)) {
            Log.d(TAG, "TimeOutHandler ===" + event.getTag() + " ===cancel");
            removeMessages(MSG_TIME_OUT);
        }
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case MSG_TIME_OUT:
                /**
                 * 收到超时消息
                 * 1.停止定位和取消转换地区码的事件投递
                 * 2.发送定位失败（fail中处理了timeout消息的remove）
                 */
                isTimeOut = true;
                Log.d(TAG, "TimeOutHandler ===" + event.getTag() + " ===timeout");
                //发送超时事件
                event.setCode(EventCode.SUCCESS);
                EventBusUtil.postEvent(event);
                break;
        }
    }


}
